package com.wrupple.muba.catalogs.client.activity.process.state;

import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.DockLayoutPanel.Direction;
import com.wrupple.muba.catalogs.client.module.services.presentation.impl.LoadEntireResultSetCallback;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.domain.FilterData;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.widget.client.view.Task;
import com.wrupple.muba.widget.client.widgets.BigFatMessage;
import com.wrupple.muba.widget.client.widgets.toolbar.Toolbar;

public class PreloadCatalogDataWithIndicator  implements Task<FilterData, List<? extends JavaScriptObject>>, Toolbar{
	
	class UpdateMessage extends DataCallback<List<JavaScriptObject>>{
		int acumulator = 0;
		@Override
		public void execute() {
			if(result!=null){
				acumulator += result.size();
				label.setTitlebarText(String.valueOf(acumulator));
			}
		}
		
	}

	private int increment;
	private String catalog;
	private BigFatMessage label;
	private StorageManager sotorageManager;
	
	public PreloadCatalogDataWithIndicator(int increment, String catalog, StorageManager sm) {
		super();
		this.increment = increment;
		this.catalog = catalog;
		this.sotorageManager=sm;
		label = new BigFatMessage(null);
	}

	@Override
	public void start(FilterData parameter, StateTransition<List<? extends JavaScriptObject>> onDone,EventBus bus) {
		StateTransition callback = onDone;
		LoadEntireResultSetCallback<JavaScriptObject> transition = new LoadEntireResultSetCallback<JavaScriptObject>(catalog,parameter,increment,sotorageManager,callback );
		transition.hook(new UpdateMessage());
		transition.start();
	}

	@Override
	public BigFatMessage asWidget() {
		return label;
	}

	@Override
	public HandlerRegistration addResizeHandler(ResizeHandler handler) {
		return label.addHandler(handler, ResizeEvent.getType());
	}

	@Override
	public void fireEvent(GwtEvent<?> event) {
		fireEvent(event);
	}

	@Override
	public Direction getDirection() {
		return Direction.NORTH;
	}

	@Override
	public int getSize() {
		return 200;
	}

}
